package com.zhkc.wisdom.common.base.context;


import cn.hutool.core.convert.Convert;
import com.alibaba.ttl.TransmittableThreadLocal;
import com.zhkc.wisdom.common.base.model.LoginContextInfo;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 获取当前线程变量中的 用户id、用户名称、Token等信息
 */
public class SecurityContextHolder {
    final static String EMPTY = "";

    private static final TransmittableThreadLocal<Map<String, Object>> THREAD_LOCAL = new TransmittableThreadLocal<>();

    protected static void set(String key, Object value) {
        Map<String, Object> map = getLocalMap();
        map.put(key, value == null ? EMPTY : value);
    }

    protected static String get(String key) {
        Map<String, Object> map = getLocalMap();
        return Convert.toStr(map.getOrDefault(key, EMPTY));
    }

    protected static <T> T get(String key, Class<T> clazz) {
        Map<String, Object> map = getLocalMap();
        return (T) map.getOrDefault(key, null);
    }

    public static Map<String, Object> getLocalMap() {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (map == null) {
            map = new ConcurrentHashMap<String, Object>();
            THREAD_LOCAL.set(map);
        }
        return map;
    }

    public static void remove() {
        THREAD_LOCAL.remove();
    }

    public static LoginContextInfo getAuthObject() {
        if (StringUtils.hasText(get(SecurityConstants.SA_AUTH_KEY))) {
            return get(SecurityConstants.SA_AUTH_KEY, LoginContextInfo.class);
        }
        return null;
    }

    public static void setAuthObject(LoginContextInfo object) {
        set(SecurityConstants.SA_AUTH_KEY, object);
    }
}
